const db = require('../db');

// 创建文件夹表
const createFoldersTable = () => {
  const sql = `
    CREATE TABLE IF NOT EXISTS folders (
      id INT AUTO_INCREMENT PRIMARY KEY,
      userId INT NOT NULL,
      name VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
      folderId INT DEFAULT NULL,
      createTime TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
      updateTime TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      FOREIGN KEY (folderId) REFERENCES folders(id) ON DELETE CASCADE
    ) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
  `;
  return db.query(sql);
};


const setFolder = async (req, res) => {
  try {
    await createFoldersTable();
    const { userId, name, folderId, id } = req.body;

    if (id) {
      // 更新现有文件夹
      const updateSql = `UPDATE folders SET name = ? WHERE id = ? AND userId = ?`;
      const [updateResult] = await db.query(updateSql, [name, id, userId]);
      if (updateResult.affectedRows === 0) {
        return res.status(404).json({ message: '文件夹未找到或无权修改' });
      }
      res.success({ data: '文件夹更新成功' });
    } else {
      // 创建新文件夹前检查是否存在同名文件夹
      const checkSql = `SELECT id FROM folders WHERE userId = ? AND name = ? AND IFNULL(folderId, 'root') = IFNULL(?, 'root')`;
      const [existingFolders] = await db.query(checkSql, [userId, name, folderId]);

      if (existingFolders.length > 0) {
        return res.status(409).json({ message: '文件夹已存在' });
      }

      // 创建新文件夹
      const insertSql = `INSERT INTO folders (userId, name, folderId) VALUES (?, ?, ?)`;
      const [insertResult] = await db.query(insertSql, [userId, name, folderId]);
      res.success({ daat: '文件夹创建成功', folderId: insertResult.insertId });
    }
  } catch (error) {
    res.status(500).json({ message: '操作文件夹失败', error });
  }
};
// 获取文件夹
const getFolders = async (req, res) => {
  try {
    await createFoldersTable();
    const { folderId, userId } = req.query;
    console.log("🚀 ~ getFolders ~ req.query:", req.query)
    const sqlFolders = `SELECT * FROM folders WHERE folderId = ? AND userId = ?`;
    const [folders] = await db.query(sqlFolders, [folderId, userId]);
    res.success({ data: folders });
  } catch (error) {
    next(error)
  }
};
// 获取文件夹内容
const getFolderContents = async (req, res) => {
  try {
    await createFoldersTable();
    const { id } = req.params;
    const sql = `
      SELECT * FROM folders WHERE folderId = ?
      UNION ALL
      SELECT * FROM files WHERE folderId = ?
    `;
    const [folders, files] = await Promise.all([
      db.query(sql, [id]),
      db.query(sql, [id])
    ]);
    res.status(200).json({ folders, files });
  } catch (error) {
    res.status(500).json({ message: 'Error fetching folder contents', error });
  }
};

// 删除文件夹
const deleteFolder = async (req, res) => {
  try {
    await createFoldersTable();
    const { id } = req.params;
    const sql = `DELETE FROM folders WHERE id = ?`;
    const [result] = await db.query(sql, [id]);
    res.success({ data: '文件夹删除成功' });
  } catch (error) {
    next(error)
  }
};
module.exports = {
  setFolder,
  getFolderContents, getFolders,
  deleteFolder,
};